package com.tk.exam.service;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.tk.exam.config.properties.SystemProperties;
import com.tk.exam.dao.TkTokenDao;
import com.tk.exam.domain.TkToken;
import com.tk.exam.domain.TkTokenExample;
import com.tk.exam.mapper.TkTokenMapper;
import com.tk.exam.vo.TkTokenVo;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@CacheConfig(cacheNames = {"tokenCache"})
public class TkTokenService {

    @Autowired
    SystemProperties systemProperties;
    @Autowired
    TkTokenMapper tkTokenMapper;
    @Autowired
    private TkTokenDao tokenDao;

    public PageInfo<TkToken> searchList(JSONObject param) {
        PageInfo<TkToken> list = tokenDao.selectAclUsersWithPage();
        return list;
    }

    public void saveToken(TkToken tkToken) {
        tkTokenMapper.insert(tkToken);
        //缓存
        ((TkTokenService) AopContext.currentProxy()).getToken(tkToken.getToken());
    }

    @CacheEvict(key = "targetClass + #tkToken.token")
    public void removeToken(TkToken tkToken) {
        tkTokenMapper.deleteByPrimaryKey(tkToken.getId());
    }

    @Cacheable(key = "targetClass + #p0")
    public TkToken getToken(String token) {
        TkTokenExample example = new TkTokenExample();
        example.or().andTokenEqualTo(token);
        List<TkToken> list = tkTokenMapper.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    @CachePut(key = "targetClass + #tkToken.token")
    @Async
    public TkToken delayToken(TkToken tkToken) {
        TkTokenVo tkTokenVo = new TkTokenVo();
        tkTokenVo.setId(tkToken.getId());
        tkTokenVo.setExpireHour(Integer.parseInt(systemProperties.getTokenExpireTime()));
        tkTokenMapper.updateExpireTimeByPrimaryKey(tkTokenVo);

        return tkTokenMapper.selectByPrimaryKey(tkToken.getId());
    }

    public void expriedToken(TkToken tkToken) {
        TkToken tkTokenDto = new TkTokenVo();
        tkTokenDto.setId(tkToken.getId());
        tkTokenDto.setIsExpired((byte) 1);
        tkTokenDto.setUpdateTime(new Date());
        tkTokenMapper.updateByPrimaryKeySelective(tkTokenDto);
    }

}
